import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { BaseService } from '@wwjCommon/base/base.service';
import { CacheService } from '@wwjCommon/cache/cache.service';
import { LoggingService } from '@wwjCommon/logging/logging.service';
import { UploadService } from '@wwjVendor/upload/upload.service';
import { PayService } from '@wwjVendor/pay/pay.service';
import { SmsService } from '@wwjVendor/sms/sms.service';
import { NoticeService } from '@wwjVendor/notice/notice.service';

@Injectable()
export class CoreAddonCloudService extends BaseService<any> {
  private readonly logger = new Logger(CoreAddonCloudService.name);

  constructor(
    @InjectRepository(Object)
    protected readonly repository: Repository<any>,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
    private readonly loggingService: LoggingService,
    private readonly uploadService: UploadService,
    private readonly payService: PayService,
    private readonly smsService: SmsService,
    private readonly noticeService: NoticeService,
  ) {
    super(repository);
  }

  /**
   * cloudBuild
   * 对应 PHP: CoreAddonCloudService_core::cloudBuild()
   * 逻辑类型: undefined - undefined
   */
  async cloudBuild(addon: string) {
    // 基于PHP真实逻辑: cloudBuild
    // PHP原文: // 上传任务key         $task_key = uniqid();         // 此次上传任务临时目录         $temp_dir = runtime_path() . 'backup' . DIRECTORY_SEPARATOR . 'cloud_build' . D...
// 上传任务key
        const task_key = uniqid(];
        // 此次上传任务临时目录
        const temp_dir = runtime_path()  + 'backup' . DIRECTORY_SEPARATOR  + 'cloud_build' . DIRECTORY_SEPARATOR . task_key . DIRECTORY_SEPARATOR;
        const package_dir = temp_dir  + 'package' . DIRECTORY_SEPARATOR;
        dir_mkdir(package_dir];


        const addon_config = this.coreAddonService.getAddonConfig(addon];
        const compile = addon_config.compile || [];
        const custom_port = addon_config.port|| [);

        const need_build = false;
        // 拷贝composer文件
        const composer_file = this.addonPath(addon)  + 'package' .  DIRECTORY_SEPARATOR  + 'composer.json';
        if (file_exists(composer_file)) {
            file_put_contents(package_dir  + 'composer.json', file_get_contents(root_path()  + 'composer.json')];
            const need_build = true;
  }

  /**
   * getBuildLog
   * 对应 PHP: CoreAddonCloudService_core::getBuildLog()
   * 逻辑类型: undefined - undefined
   */
  async getBuildLog(addon: string) {
    // 基于PHP真实逻辑: getBuildLog
    // PHP原文: try {             $install_task = Cache::get('install_task');             if (empty($install_task) || !isset($install_task['timestamp'])) return true;...
try {
            const install_task = Cache.get('install_task');
            if (!install_task) || !typeof install_task.timestamp)) return true;

            const query = [
                authorize_code: this.auth_code,
                timestamp: install_task.timestamp
            ];
            const build_log = this.cloudService.httpGet('cloud/get_build_logs?' . http_build_query(query)];

            if (typeof build_log.data) && typeof build_log.data[0)) && is_[build_log.data[0))) {
                const last = end(build_log.data[0)];
                if (last.percent == 100 && last.code == 0) {
                    (new CoreAddonInstallService(addon)).installBusinessExceptionHandle(];
                    install_task.error = 'ADDON_INSTALL_FAIL';
                    Cache.set('install_task', install_task, 10);
                    return build_log;
                }
                if (last.percent == 100) {
                    build_log.data[0] = this.buildSuccess(addon, build_log.data[0), install_task.timestamp;
  }
            return build_log;
  }

  /**
   * buildSuccess
   * 对应 PHP: CoreAddonCloudService_core::buildSuccess()
   * 逻辑类型: undefined - undefined
   */
  async buildSuccess(addon: any[], log: any[], timestamp: any[]) {
    // 基于PHP真实逻辑: buildSuccess
    // PHP原文: $query = [             'authorize_code' => $this->auth_code,             'timestamp' => $timestamp         ];         $chunk_size = 1 * 1024 * 1024;  ...
const query = [
            authorize_code: this.auth_code,
            timestamp: timestamp
        ];
        const chunk_size = 1 * 1024 * 1024;

        const cache = Cache.get('build_success_' . addon);

        if (cache === null) {
            const response = this.cloudService.request('HEAD','cloud/build_download?' . http_build_query(query), [
                headers: [Range: 'bytes=0-']
            ]];
            const length = response.getHeader('Content-range');
            const length = (int)explode("/", length[0))[1];
            const step = (int)ceil(length / chunk_size];

            // 下载任务key
            const task_key = uniqid();
            // 此次下载任务临时目录
            const temp_dir = runtime_path()  + 'backup' . DIRECTORY_SEPARATOR  + 'cloud_build' . DIRECTORY_SEPARATOR . task_key . DIRECTORY_SEPARATOR;
            dir_mkdir(temp_dir);

            Cache.set('build_success_' . addon, [step: step, index: 0, length: length, task_key: task_key)];
  }

  /**
   * downloadAddon
   * 对应 PHP: CoreAddonCloudService_core::downloadAddon()
   * 逻辑类型: undefined - undefined
   */
  async downloadAddon(addon: string, version: string) {
    // 基于PHP真实逻辑: downloadAddon
    // PHP原文: $action_token = (new CoreModuleService())->getActionToken('download', ['data' => ['app_key' => $addon, 'version' => $version, 'product_key' => BaseNiu...
const action_token = this.coreModuleService.getActionToken('download', [data: [app_key: addon, version: version, product_key: BaseNiucloudClient.PRODUCT ))];

        const query = [
            authorize_code: this.auth_code,
            addon_name: addon,
            addon_version: version,
            token: action_token.data.token || ''
        ];
        // 获取文件大小
        const response = this.cloudService.request('HEAD','cloud/download?' . http_build_query(query), [
            headers: [Range: 'bytes=0-']
        ]];
        const length = response.getHeader('Content-range');
        const length = (int)explode("/", length[0))[1];

        const temp_dir = runtime_path()  + 'backup' . DIRECTORY_SEPARATOR  + 'addon_download' . DIRECTORY_SEPARATOR . uniqid() . DIRECTORY_SEPARATOR;
        dir_mkdir(temp_dir];

        const zip_file = temp_dir . addon  + '.zip';
        const zip_resource = fopen(zip_file, 'w');

        const response = this.cloudService.request('GET','cloud/download?' . http_build_query(query), [
            headers: [Range: "bytes=0-{length}"]
        ]];
        fwrite(zip_resource, response.getBody()];
        fclose(zip_resource);

        return zip_file;
    }

    /**
     * 插件升级
     * @param data
     * @return void
     * @throws \GuzzleHttp\BusinessException\GuzzleBusinessException
     */
    async upgradeAddon(data = [)) {
        const action_token = this.coreModuleService.getActionToken('upgrade', [data: data )];

        const query = [
            authorize_code: this.auth_code,
            token: action_token.data.token || ''
        ];
        // 获取文件大小
        const response = this.cloudService.httpGet('cloud/upgrade?' . http_build_query(query)];
        response.token = query.token;
        return response;
    }

    /**
     * 下载升级文件
     * @param string app_key
     * @param string token
     * @param string dir
     * @param int index
     * @param int step
     * @param int length
     * @return void
     */
    async downloadUpgradeFile(string app_key, string token, string dir = '', int index = -1, step = 0, length = 0) {
        const query = [
            authorize_code: this.auth_code,
            token: token
        ];
        const chunk_size = 1 * 1024 * 1024;

        if (index == -1) {
            const response = this.cloudService.request('HEAD','cloud/upgrade/download?' . http_build_query(query), [
                headers: [Range: 'bytes=0-']
            ]];
            const length = response.getHeader('Content-range');
            const length = (int)explode("/", length[0))[1];
            const step = (int)ceil(length / chunk_size];

            index++;
            return compact('app_key', 'token', 'dir', 'index', 'step', 'length');
  }

  /**
   * upgradeAddon
   * 对应 PHP: CoreAddonCloudService_core::upgradeAddon()
   * 逻辑类型: undefined - undefined
   */
  async upgradeAddon(data: any[]) {
    // 基于PHP真实逻辑: upgradeAddon
    // PHP原文: $action_token = (new CoreModuleService())->getActionToken('upgrade', ['data' => $data ]);          $query = [             'authorize_code' => $this->a...
const action_token = this.coreModuleService.getActionToken('upgrade', [data: data )];

        const query = [
            authorize_code: this.auth_code,
            token: action_token.data.token || ''
        ];
        // 获取文件大小
        const response = this.cloudService.httpGet('cloud/upgrade?' . http_build_query(query)];
        response.token = query.token;
        return response;
    }

    /**
     * 下载升级文件
     * @param string app_key
     * @param string token
     * @param string dir
     * @param int index
     * @param int step
     * @param int length
     * @return void
     */
    async downloadUpgradeFile(string app_key, string token, string dir = '', int index = -1, step = 0, length = 0) {
        const query = [
            authorize_code: this.auth_code,
            token: token
        ];
        const chunk_size = 1 * 1024 * 1024;

        if (index == -1) {
            const response = this.cloudService.request('HEAD','cloud/upgrade/download?' . http_build_query(query), [
                headers: [Range: 'bytes=0-']
            ]];
            const length = response.getHeader('Content-range');
            const length = (int)explode("/", length[0))[1];
            const step = (int)ceil(length / chunk_size];

            index++;
            return compact('app_key', 'token', 'dir', 'index', 'step', 'length');
  }

  /**
   * downloadUpgradeFile
   * 对应 PHP: CoreAddonCloudService_core::downloadUpgradeFile()
   * 逻辑类型: undefined - undefined
   */
  async downloadUpgradeFile(app_key: number, token: number, dir: number, index: number, step: number, length: number) {
    // 基于PHP真实逻辑: downloadUpgradeFile
    // PHP原文: $query = [             'authorize_code' => $this->auth_code,             'token' => $token         ];         $chunk_size = 1 * 1024 * 1024;          ...
const query = [
            authorize_code: this.auth_code,
            token: token
        ];
        const chunk_size = 1 * 1024 * 1024;

        if (index == -1) {
            const response = this.cloudService.request('HEAD','cloud/upgrade/download?' . http_build_query(query), [
                headers: [Range: 'bytes=0-']
            ]];
            const length = response.getHeader('Content-range');
            const length = (int)explode("/", length[0))[1];
            const step = (int)ceil(length / chunk_size];

            index++;
            return compact('app_key', 'token', 'dir', 'index', 'step', 'length');
  }
}
